package com.eningqu.aipen.demo.adapter;

import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.TextView;

import com.eningqu.aipen.demo.R;
import com.eningqu.aipen.sdk.bean.device.NQBtDevice;
import com.eningqu.aipen.sdk.bean.device.NQDeviceBase;
import com.eningqu.aipen.sdk.bean.device.NQUsbDevice;

import java.util.List;

/**
 * author : LiQiu
 * e-mail : lq@eningqu.com
 * date   : 2020/11/20 20:02
 * desc   : 设备展示列表适配器
 * version: 1.0
 */
public class DeviceAdapter extends BaseAdapter {
    Context context;
    LayoutInflater inflater;

    List<NQDeviceBase> devices;

    public DeviceAdapter(Context context, List<NQDeviceBase> devices) {
        this.context = context;
        inflater = LayoutInflater.from(context);
        this.devices = devices;
    }

    @Override
    public int getCount() {
        return devices.size();
    }

    @Override
    public Object getItem(int position) {
        return devices.get(position);
    }

    @Override
    public long getItemId(int position) {
        return position;
    }

    @Override
    public View getView(int position, View convertView, ViewGroup parent) {
        ViewGroup vg;

        if (convertView != null) {
            vg = (ViewGroup) convertView;
        } else {
            vg = (ViewGroup) inflater.inflate(R.layout.device_list_element, null);
        }

        NQDeviceBase device = devices.get(position);
        final TextView tvadd = ((TextView) vg.findViewById(R.id.address));
        final TextView tvname = ((TextView) vg.findViewById(R.id.name));
        final TextView tvpaired = (TextView) vg.findViewById(R.id.paired);
        //final TextView tvrssi = (TextView) vg.findViewById(R.id.rssi);
        if("usb".equals(device.getType())){
            NQUsbDevice nqUsbDevice = (NQUsbDevice) device;

            String pid = Integer.toHexString(nqUsbDevice.getDevice().getProductId());
            String vid = Integer.toHexString(nqUsbDevice.getDevice().getVendorId());

            pid = pid.length()==1?"000"+pid.toUpperCase():pid.toUpperCase();
            vid = vid.length()==1?"000"+vid.toUpperCase():vid.toUpperCase();

            pid = pid.length()==2?"00"+pid.toUpperCase():pid.toUpperCase();
            vid = vid.length()==2?"00"+vid.toUpperCase():vid.toUpperCase();

            pid = pid.length()==3?"0"+pid.toUpperCase():pid.toUpperCase();
            vid = vid.length()==3?"0"+vid.toUpperCase():vid.toUpperCase();

            tvname.setText("PID: "+pid);
            tvadd.setText("VID: "+vid);
            tvpaired.setText("");
        } else if("bt".equals(device.getType())){
            NQBtDevice nqBleDevice = (NQBtDevice) device;

            tvname.setText(nqBleDevice.name);
            tvadd.setText(nqBleDevice.mac);
            tvpaired.setText("");
        }
        //tvrssi.setText("Rssi = ");
        return vg;
    }
}
